<template>
  <UploadFile
    class="w-100%"
    url="/common/uploadFile"
    drag
    :file-type="[
      'png',
      'jpg',
      'jpeg',
      'bmp',
      'pdf',
      'docx',
      'doc',
      'xlsx',
      'xls',
      'mp4',
      'avi',
      'mov',
      'wmv',
      'flv',
      'mkv',
      'webm',
      '3gp',
      'm4v',
      'mp3',
      'wav',
      'flac',
      'aac'
    ]"
    :file-size="1024"
    :params="{ directory: 11 }"
    :limit="9"
    upload-file-button-name="点击上传或拖拽到此处上传"
    buttonWidth="100%"
    :button-link="true"
    :show-file-list="true"
    @upload-success-res="handleUploadCallback"
  />

  <div v-if="files.length > 0" class="files-container">
    <div v-for="(file, index) in files" :key="index" class="file-info">
      <div class="file-header">
        <span class="file-index">文件 {{ index + 1 }}</span>
      </div>
      <div class="file-item">
        <el-text tag="b">文件名称：{{ file.name }}</el-text>
      </div>
      <div class="file-item">
        <el-text tag="b">文件地址：{{ file.url }}</el-text>
      </div>

      <div class="button-group">
        <el-button type="primary" @click="previewFile(file.url)">预览</el-button>
        <el-button type="success" @click="copyFileUrl(file.url)">复制</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'

interface FileItem {
  name: string
  url: string
}

const files = reactive<FileItem[]>([])

//上传成功以后回调
const handleUploadCallback = (val: any) => {
  console.log(val)
  // 追加新文件到数组中
  files.push({
    name: val.name,
    url: val.url
  })
}

// 预览文件 - 新标签页打开
const previewFile = (url: string) => {
  if (url) {
    window.open(url, '_blank')
  } else {
    ElMessage.warning('没有可预览的文件')
  }
}

// 复制文件链接
const copyFileUrl = async (url: string) => {
  if (!url) {
    ElMessage.warning('没有可复制的文件链接')
    return
  }

  try {
    await navigator.clipboard.writeText(url)
    ElMessage.success('文件链接已复制到剪贴板')
  } catch (err) {
    // 如果navigator.clipboard不可用，使用备用方法
    const textArea = document.createElement('textarea')
    textArea.value = url
    document.body.appendChild(textArea)
    textArea.focus()
    textArea.select()
    try {
      document.execCommand('copy')
      ElMessage.success('文件链接已复制到剪贴板')
    } catch (err) {
      ElMessage.error('复制失败，请手动复制')
    }
    document.body.removeChild(textArea)
  }
}
</script>

<style scoped>
.files-container {
  margin-top: 20px;
}

.file-info {
  padding: 15px;
  margin-bottom: 20px;
  background-color: #fafafa;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
}

.file-header {
  margin-bottom: 10px;
}

.file-index {
  font-size: 14px;
  font-weight: bold;
  color: #409eff;
}

.file-item {
  margin-bottom: 10px;
}

.button-group {
  display: flex;
  margin-top: 15px;
  gap: 10px;
}
</style>
